<script setup lang="ts">
  import { ref, onMounted, computed, onUnmounted } from 'vue'
  import { useRouter } from 'vue-router'
  import type { Tag } from '@/types/api'
  import { list as getTagList } from '@/api/tag'

  const router = useRouter()
  const loading = ref(true)
  const tags = ref<(Tag & { color: string })[]>([])
  const searchKeyword = ref('')
  const viewMode = ref<'grid' | 'list' | 'cloud'>('grid')
  const sortType = ref<'name' | 'count'>('count')
  const sortOrder = ref<'asc' | 'desc'>('desc')
  const showSortDropdown = ref(false)

  // 排序选项
  const sortOptions = [
    { value: 'count', label: '按文章数量', icon: '📊' },
    { value: 'name', label: '按名称', icon: '🔤' },
  ]

  // 预定义的标签颜色
  const tagColors: { [key: string]: string } = {
    'Vue.js': '#4FC08D',
    Vue: '#4FC08D',
    JavaScript: '#F7DF1E',
    TypeScript: '#3178C6',
    React: '#61DAFB',
    CSS: '#1572B6',
    'Node.js': '#339933',
    Webpack: '#8DD6F9',
    前端工程化: '#FF6B6B',
    HTML: '#E34C26',
    Java: '#007396',
    Spring: '#6DB33F',
    Python: '#3776AB',
    Git: '#F05032',
    Docker: '#2496ED',
    MySQL: '#4479A1',
    Redis: '#DC382D',
    Linux: '#FCC624',
    Nginx: '#009639',
  }

  // 过滤后的标签
  const filteredTags = computed(() => {
    let result = tags.value

    // 搜索过滤
    if (searchKeyword.value) {
      result = result.filter(tag =>
        tag.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
      )
    }

    // 排序
    result.sort((a, b) => {
      let comparison = 0
      switch (sortType.value) {
        case 'name':
          comparison = a.name.localeCompare(b.name)
          break
        case 'count':
          comparison = a.count - b.count
          break
      }
      return sortOrder.value === 'desc' ? -comparison : comparison
    })

    return result
  })

  // 热门标签 (前10个)
  const hotTags = computed(() => {
    return [...tags.value].sort((a, b) => b.count - a.count).slice(0, 10)
  })

  // 统计信息
  const stats = computed(() => {
    const totalTags = tags.value.length
    console.log(tags.value)
    const totalArticles = tags.value.reduce((sum, tag) => sum + tag.count, 0)
    const avgArticlesPerTag = totalTags > 0 ? Math.round((totalArticles / totalTags) * 10) / 10 : 0
    const hottest = tags.value.reduce(
      (max, tag) => (tag.count > max.count ? tag : max),
      tags.value[0] || { name: '-', count: 0 }
    )

    console.log(totalTags, totalArticles, avgArticlesPerTag, hottest)
    return {
      totalTags,
      totalArticles,
      avgArticlesPerTag,
      hottestTag: hottest,
    }
  })

  // 获取标签图标
  const getTagIcon = (tag: Tag) => {
    return tag.icon || '🏷️'
  }

  // 切换排序下拉菜单
  const toggleSortDropdown = () => {
    showSortDropdown.value = !showSortDropdown.value
  }

  // 处理排序选择
  const handleSortSelect = (sort: string) => {
    if (sortType.value === sort) {
      sortOrder.value = sortOrder.value === 'desc' ? 'asc' : 'desc'
    } else {
      sortType.value = sort as 'name' | 'count'
      sortOrder.value = 'desc'
    }
    toggleSortDropdown()
  }

  // 获取排序文本
  const getSortText = () => {
    const option = sortOptions.find(opt => opt.value === sortType.value)
    const orderText = sortOrder.value === 'desc' ? '↓' : '↑'
    return `${option?.label || '排序'} ${orderText}`
  }

  // 点击外部关闭下拉菜单
  const handleClickOutside = (event: Event) => {
    const target = event.target as HTMLElement
    if (!target.closest('.sort-dropdown')) {
      showSortDropdown.value = false
    }
  }

  // 加载标签数据
  const loadTags = async () => {
    try {
      loading.value = true
      const response = await getTagList()
      tags.value = (response || [])
        .filter(tag => tag.count > 0) // 过滤掉文章数为0的标签
        .map((tag: Tag) => ({
          ...tag,
          color:
            tag.color ||
            tagColors[tag.name] ||
            `#${Math.floor(Math.random() * 16777215).toString(16)}`,
        }))
    } catch (error) {
      console.error('加载标签失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 处理标签点击
  const handleTagClick = (tag: Tag & { color: string }) => {
    router.push(`/tags/${tag.id}`)
  }

  // 清空搜索
  const clearSearch = () => {
    searchKeyword.value = ''
  }

  onMounted(async () => {
    document.addEventListener('click', handleClickOutside)
    await loadTags()
  })

  onUnmounted(() => {
    document.removeEventListener('click', handleClickOutside)
  })
</script>

<template>
  <div class="tag-list-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <h1 class="page-title">🏷️ 文章标签</h1>
        <p class="page-subtitle">通过标签快速找到感兴趣的内容</p>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-layout">
        <!-- 主内容区域 -->
        <main class="main-content">
          <!-- 工具栏 -->
          <div class="toolbar">
            <!-- 搜索框 -->
            <div class="search-box">
              <input
                v-model="searchKeyword"
                type="text"
                placeholder="搜索标签..."
                class="search-input"
              />
              <button v-if="searchKeyword" class="clear-btn" @click="clearSearch">✕</button>
              <span class="search-icon">🔍</span>
            </div>

            <!-- 视图切换 -->
            <div class="view-switcher">
              <button
                class="view-btn"
                :class="{ active: viewMode === 'grid' }"
                title="网格视图"
                @click="viewMode = 'grid'"
              >
                ⊞
              </button>
              <button
                class="view-btn"
                :class="{ active: viewMode === 'list' }"
                title="列表视图"
                @click="viewMode = 'list'"
              >
                ≡
              </button>
              <button
                class="view-btn"
                :class="{ active: viewMode === 'cloud' }"
                title="标签云"
                @click="viewMode = 'cloud'"
              >
                ☁️
              </button>
            </div>

            <!-- 排序选择 -->
            <div class="sort-dropdown">
              <button class="sort-trigger" @click="toggleSortDropdown">
                <span>{{ getSortText() }}</span>
                <span class="arrow" :class="{ open: showSortDropdown }">▼</span>
              </button>
              <div v-if="showSortDropdown" class="sort-options">
                <div
                  v-for="option in sortOptions"
                  :key="option.value"
                  class="sort-option"
                  :class="{ active: sortType === option.value }"
                  @click="handleSortSelect(option.value)"
                >
                  <span class="option-icon">{{ option.icon }}</span>
                  <span>{{ option.label }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 标签展示区域 -->
          <div class="tags-container">
            <!-- 加载状态 -->
            <div v-if="loading" class="loading-skeleton">
              <div v-for="i in 12" :key="i" class="skeleton-item" :class="viewMode"></div>
            </div>

            <!-- 空状态 -->
            <div v-else-if="filteredTags.length === 0" class="empty-state">
              <div class="empty-icon">🔍</div>
              <h3>未找到相关标签</h3>
              <p>尝试调整搜索条件</p>
              <button class="reset-btn" @click="searchKeyword = ''">重置搜索</button>
            </div>

            <!-- 网格视图 -->
            <div v-else-if="viewMode === 'grid'" class="tags-grid">
              <div
                v-for="tag in filteredTags"
                :key="tag.id"
                class="tag-card"
                :style="{ '--tag-color': tag.color }"
                @click="handleTagClick(tag)"
              >
                <div class="tag-header">
                  <span class="tag-icon">{{ getTagIcon(tag) }}</span>
                  <h4 class="tag-name">{{ tag.name }}</h4>
                </div>
                <div class="tag-stats">
                  <div class="stat-item">
                    <span class="stat-label">文章</span>
                    <span class="stat-value">{{ tag.count }}篇</span>
                  </div>
                </div>
                <button class="view-detail-btn">查看详情</button>
              </div>
            </div>

            <!-- 列表视图 -->
            <div v-else-if="viewMode === 'list'" class="tags-list">
              <div
                v-for="tag in filteredTags"
                :key="tag.id"
                class="tag-list-item"
                :style="{ '--tag-color': tag.color }"
                @click="handleTagClick(tag)"
              >
                <span class="tag-icon">{{ getTagIcon(tag) }}</span>
                <span class="tag-name">{{ tag.name }}</span>
                <span class="tag-count">[{{ tag.count }}篇文章]</span>
              </div>
            </div>

            <!-- 标签云视图 -->
            <div v-else-if="viewMode === 'cloud'" class="tags-cloud">
              <div
                v-for="tag in filteredTags"
                :key="tag.id"
                class="cloud-tag"
                :style="{
                  '--tag-color': tag.color,
                  fontSize: `${0.8 + (tag.count / Math.max(...filteredTags.map(t => t.count))) * 1.2}rem`,
                }"
                @click="handleTagClick(tag)"
              >
                {{ tag.name }}
              </div>
            </div>
          </div>
        </main>

        <!-- 右侧信息栏 -->
        <aside class="info-panel">
          <!-- 统计信息 -->
          <div class="panel-section">
            <h3 class="section-title">📊 标签统计</h3>
            <div class="stats-grid">
              <div class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ stats.totalTags }}</div>
                  <div class="stat-label">总标签数</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ stats.totalArticles }}</div>
                  <div class="stat-label">总文章数</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ stats.avgArticlesPerTag }}</div>
                  <div class="stat-label">平均每标签</div>
                </div>
              </div>
              <div class="stat-card">
                <div class="stat-content">
                  <div class="stat-number">{{ stats.hottestTag.name }}</div>
                  <div class="stat-label">最热标签</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 热门标签排行 -->
          <div class="panel-section">
            <h3 class="section-title">🏆 热门排行</h3>
            <div class="hot-tags-list">
              <div
                v-for="(tag, index) in hotTags"
                :key="tag.id"
                class="hot-tag-item"
                @click="handleTagClick(tag)"
              >
                <span class="rank">{{ index + 1 }}</span>
                <span class="tag-name">{{ tag.name }}</span>
                <span class="tag-count">{{ tag.count }}</span>
              </div>
            </div>
          </div>
        </aside>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .tag-list-page {
    min-height: 100vh;
    padding: 2rem 0;
    background-color: var(--bg-color);
  }

  .page-header {
    text-align: center;
    margin-bottom: 2rem;

    .page-title {
      font-size: 2.5rem;
      font-weight: 700;
      color: var(--text-primary);
      margin: 0 0 0.5rem 0;
    }

    .page-subtitle {
      font-size: 1.1rem;
      color: var(--text-secondary);
      margin: 0;
    }
  }

  /* 主布局 */
  .main-layout {
    display: grid;
    grid-template-columns: 1fr 280px;
    gap: 2rem;
    align-items: start;
  }

  /* 主内容区域 */
  .main-content {
    background: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-xl);
    padding: 2rem;
    min-height: 600px;
  }

  /* 工具栏 */
  .toolbar {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 2rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid var(--border-color);
    flex-wrap: wrap;
  }

  /* 搜索框 */
  .search-box {
    position: relative;
    flex: 1;
    min-width: 200px;

    .search-input {
      width: 100%;
      padding: 0.75rem 3rem 0.75rem 1rem;
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      background: var(--bg-secondary);
      color: var(--text-primary);
      font-size: 0.9rem;
      transition: all 0.3s ease;

      &:focus {
        outline: none;
        border-color: var(--primary-color);
        background: var(--bg-color);
      }

      &::placeholder {
        color: var(--text-secondary);
      }
    }

    .search-icon {
      position: absolute;
      right: 1rem;
      top: 50%;
      transform: translateY(-50%);
      color: var(--text-secondary);
      pointer-events: none;
    }

    .clear-btn {
      position: absolute;
      right: 2.5rem;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      color: var(--text-secondary);
      cursor: pointer;
      padding: 0.25rem;
      border-radius: 50%;
      transition: all 0.2s ease;

      &:hover {
        background: var(--bg-secondary);
        color: var(--text-primary);
      }
    }
  }

  /* 视图切换 */
  .view-switcher {
    display: flex;
    border: 1px solid var(--border-color);
    border-radius: var(--radius-lg);
    overflow: hidden;

    .view-btn {
      padding: 0.75rem 1rem;
      background: var(--bg-secondary);
      border: none;
      color: var(--text-secondary);
      cursor: pointer;
      transition: all 0.2s ease;
      font-size: 1rem;

      &:hover {
        background: var(--bg-tertiary);
        color: var(--text-primary);
      }

      &.active {
        background: var(--primary-color);
        color: white;
      }

      &:not(:last-child) {
        border-right: 1px solid var(--border-color);
      }
    }
  }

  /* 排序下拉 */
  .sort-dropdown {
    position: relative;

    .sort-trigger {
      display: flex;
      align-items: center;
      gap: 0.5rem;
      padding: 0.75rem 1rem;
      background: var(--bg-secondary);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      color: var(--text-primary);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: var(--primary-color);
        background: var(--bg-tertiary);
      }

      .arrow {
        font-size: 0.7rem;
        transition: transform 0.3s ease;

        &.open {
          transform: rotate(180deg);
        }
      }
    }

    .sort-options {
      position: absolute;
      top: 100%;
      right: 0;
      background: var(--bg-color);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      box-shadow: var(--shadow-lg);
      z-index: 100;
      margin-top: 0.25rem;
      min-width: 150px;
      overflow: hidden;

      .sort-option {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1rem;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          background: var(--bg-secondary);
        }

        &.active {
          background: var(--primary-light);
          color: var(--primary-color);
        }

        .option-icon {
          font-size: 0.9rem;
        }
      }
    }
  }

  /* 加载骨架屏 */
  .loading-skeleton {
    display: grid;
    gap: 1rem;

    &.grid {
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }

    &.list {
      grid-template-columns: 1fr;
    }

    &.cloud {
      display: flex;
      flex-wrap: wrap;
      gap: 0.5rem;
    }

    .skeleton-item {
      background: linear-gradient(
        90deg,
        var(--bg-secondary) 25%,
        var(--bg-tertiary) 50%,
        var(--bg-secondary) 75%
      );
      background-size: 200% 100%;
      animation: shimmer 1.5s infinite;
      border-radius: var(--radius-lg);

      &.grid {
        height: 120px;
      }

      &.list {
        height: 60px;
      }

      &.cloud {
        height: 2rem;
        width: 80px;
      }
    }
  }

  @keyframes shimmer {
    0% {
      background-position: -200% 0;
    }
    100% {
      background-position: 200% 0;
    }
  }

  /* 空状态 */
  .empty-state {
    text-align: center;
    padding: 4rem 2rem;
    color: var(--text-secondary);

    .empty-icon {
      font-size: 4rem;
      margin-bottom: 1rem;
    }

    h3 {
      font-size: 1.5rem;
      margin: 0 0 0.5rem 0;
      color: var(--text-primary);
    }

    p {
      margin: 0 0 2rem 0;
    }

    .reset-btn {
      padding: 0.75rem 2rem;
      background: var(--primary-color);
      color: white;
      border: none;
      border-radius: var(--radius-lg);
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: var(--primary-color-dark);
        transform: translateY(-2px);
      }
    }
  }

  /* 网格视图 */
  .tags-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;

    .tag-card {
      background: var(--bg-secondary);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      padding: 1.5rem;
      cursor: pointer;
      transition: all 0.3s ease;
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 3px;
        background: var(--tag-color);
        transform: scaleX(0);
        transition: transform 0.3s ease;
      }

      &:hover {
        transform: translateY(-5px);
        box-shadow: var(--shadow-lg);
        border-color: var(--tag-color);

        &::before {
          transform: scaleX(1);
        }

        .view-detail-btn {
          background: var(--tag-color);
          color: white;
        }
      }

      .tag-header {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        margin-bottom: 1rem;

        .tag-icon {
          font-size: 1.5rem;
        }

        .tag-name {
          font-size: 1.1rem;
          font-weight: 600;
          color: var(--text-primary);
          margin: 0;
        }
      }

      .tag-stats {
        margin-bottom: 1rem;

        .stat-item {
          display: flex;
          justify-content: space-between;
          align-items: center;

          .stat-label {
            font-size: 0.9rem;
            color: var(--text-secondary);
          }

          .stat-value {
            font-size: 1rem;
            font-weight: 600;
            color: var(--tag-color);
          }
        }
      }

      .view-detail-btn {
        width: 100%;
        padding: 0.5rem;
        background: var(--bg-tertiary);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-sm);
        color: var(--text-primary);
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 0.9rem;
      }
    }
  }

  /* 列表视图 */
  .tags-list {
    .tag-list-item {
      display: flex;
      align-items: center;
      gap: 1rem;
      padding: 1rem;
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      margin-bottom: 0.75rem;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: var(--tag-color);
        background: var(--bg-secondary);
        transform: translateX(5px);
      }

      .tag-icon {
        font-size: 1.2rem;
        flex-shrink: 0;
      }

      .tag-name {
        font-weight: 600;
        color: var(--text-primary);
        flex: 1;
      }

      .tag-count {
        color: var(--tag-color);
        font-weight: 500;
      }
    }
  }

  /* 标签云视图 */
  .tags-cloud {
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    justify-content: center;
    align-items: center;
    padding: 2rem;

    .cloud-tag {
      display: inline-block;
      padding: 0.5rem 1rem;
      background: var(--bg-secondary);
      border: 2px solid var(--border-color);
      border-radius: var(--radius-lg);
      color: var(--text-primary);
      cursor: pointer;
      transition: all 0.3s ease;
      font-weight: 600;

      &:hover {
        background: var(--tag-color);
        border-color: var(--tag-color);
        color: white;
        transform: scale(1.1) translateY(-3px);
        box-shadow: var(--shadow-lg);
      }
    }
  }

  /* 右侧信息栏 */
  .info-panel {
    background: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: var(--radius-xl);
    padding: 1.5rem;

    .panel-section {
      margin-bottom: 2rem;

      &:last-child {
        margin-bottom: 0;
      }
    }

    .section-title {
      font-size: 1rem;
      font-weight: 600;
      color: var(--text-primary);
      margin: 0 0 1rem 0;
      border-bottom: 1px solid var(--border-color);
      padding-bottom: 0.5rem;
    }
  }

  /* 统计网格 */
  .stats-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;

    .stat-card {
      background: var(--bg-secondary);
      border: 1px solid var(--border-color);
      border-radius: var(--radius-lg);
      padding: 1rem;
      text-align: center;
      .stat-content {
        height: 100%;
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
      }

      .stat-number {
        font-size: 1.2rem;
        font-weight: 700;
        color: var(--primary-color);
        margin-bottom: 0.25rem;
        line-height: 1;
      }

      .stat-label {
        font-size: 0.9rem;
        color: var(--text-secondary);
      }
    }
  }

  /* 针对最热标签的数字样式单独加粗并略大 */
  .stats-grid .stat-card:last-child .stat-number {
    font-size: 1.1rem;
    font-weight: 700;
    letter-spacing: 0.5px;
  }

  /* 热门标签列表 */
  .hot-tags-list {
    .hot-tag-item {
      display: flex;
      align-items: center;
      gap: 0.75rem;
      padding: 0.75rem;
      border-radius: var(--radius-lg);
      cursor: pointer;
      transition: all 0.2s ease;
      margin-bottom: 0.5rem;

      &:hover {
        background: var(--bg-secondary);
      }

      .rank {
        width: 1.5rem;
        height: 1.5rem;
        background: var(--primary-color);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 0.8rem;
        font-weight: 600;
        flex-shrink: 0;
      }

      .tag-name {
        flex: 1;
        font-size: 0.9rem;
        color: var(--text-primary);
      }

      .tag-count {
        font-size: 0.8rem;
        color: var(--text-secondary);
        font-weight: 500;
      }
    }
  }

  /* 响应式设计 */
  @media (max-width: 1024px) {
    .main-layout {
      grid-template-columns: 1fr;
    }

    .info-panel {
      position: static;
      max-height: none;
    }

    .toolbar {
      flex-direction: column;
      align-items: stretch;
      gap: 1rem;
    }

    .search-box {
      min-width: auto;
    }

    .view-switcher {
      justify-self: center;
    }

    .tags-grid {
      grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    }

    .stats-grid {
      grid-template-columns: 1fr 1fr;
    }
  }

  @media (max-width: 768px) {
    .toolbar {
      flex-direction: column;
      align-items: stretch;
      gap: 1rem;
    }

    .tags-grid {
      grid-template-columns: 1fr;
    }

    .stats-grid {
      grid-template-columns: 1fr;
    }
  }

  @media (max-width: 480px) {
    .tag-list-page {
      padding: 1rem 0;
    }

    .page-header .page-title {
      font-size: 2rem;
    }

    .main-content {
      padding: 1rem;
    }

    .info-panel {
      padding: 1rem;
    }

    .tags-cloud {
      padding: 1rem;
      gap: 0.5rem;
    }
  }
</style>
